<?php

/*
*/

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Purchase extends CI_Controller {

	public $data;
	private $access_id = 200;
	private $limit = 15;
	private $error = '';

	public function __construct()
	{
		parent::__construct();
		//载入必要类文件
		$this->load->model('Purchase_Application_model');
		$this->load->model('Order_model');
		$this->load->model('Order_Detail_model');
		$this->load->model('User_model');
		$this->load->model('Right_model');
		$this->load->model('Goods_type_model');
		$this->load->model('Main_goods_model');
		$this->load->model('Sub_goods_model');
		$this->load->model('Supplier_model');
		$this->load->model('Suppliers_Goods_model');
		//载入必要库文件
		$this->load->library('pagination');
		$this->load->library('Access_control');
		$this->load->library('Menu_control');
		$this->load->library('Forbid_resubmit');
		//载入配置文件 并 初始化控制器
		$this->data['site'] = $this->config->item('site');
		$this->data['order_status'] = $this->config->item('order_status');
		$this->data['purapp_status'] = $this->config->item('purapp_status');
		$this->data['title'] = '货品管理';
		$this->data['styles'] = array('error.css', 'purchase.css');
		$this->data['scripts'] = array('master.js', 'purchase.js', 'order.js');
		//检查是否是登录用户
		if (!$this->User_model->checkLoginedUser())
		{
			$this->data['error'] = '登录超时，请重新登录';
			$this->load->view_('error_500_view', $this->data);
			return;
		}
		//设置站点基本参数
		$this->data['cur_user'] = $this->User_model->getUser($this->input->cookie('user_id'));
		$this->data['header']['username'] = $this->data['cur_user']['realname'];
		$this->data['site']['environment'] = $this->User_model->get_envrionment();
		$this->data['menus'] = $this->User_model->userMenus($this->config->item('menus'), $this->data['cur_user']['rights']);
		$this->data['menus'] = $this->menu_control->main($this->data['menus'], 2);
		$this->data['sub_menus'] = $this->_menus();
		$this->data['sub_menu_index'] = '-1';
		//全局访问控制
		if (!$this->access_control->base(0, $this->data['cur_user']['rights']))
		{
			$this->data['error'] = '拒绝访问';
			$this->load->view_('error_500_view', $this->data);
		}
	}

	private function _menus()
	{
		
		return array(
			array(
				'index'	=>	4,
				'access'=>	0,
				'url'	=>	$this->data['site']['root'] . 'purchase/order/list/',
				'name'	=>	'订货单'
			),
			array(
				'index' =>	3,
				'access'=>	0,
				'url'	=>	$this->data['site']['root'] . 'purchase/create/',
				'name'	=>	'新建订货'
			),
			array(
				'index'	=>	0,
			),
			array(
				'index'	=>	1,
				'access'=>	0,
				'url'	=>	$this->data['site']['root'] . 'purchase/application/create/',
				'name'	=>	'申请采购'
			),
			array(
				'index'	=>	2,
				'access'=>	0,
				'url'	=>	$this->data['site']['root'] . 'purchase/application/list/',
				'name'	=>	'采购申请单'
			),
		);
	}

	public function index()
	{
		$this->application('list');
	}

	public function create($pur_app_id=0)
	{
		$this->data['sub_menu_index'] = 3;
		if (true == $this->input->post('create'))
		{
			//验证表单有效性
			$sub_goods_ids = $this->input->post('sub_goods_ids');
			$supplier_ids = $this->input->post('supplier_ids');
			$single_prices = $this->input->post('single_prices');
			$quantities = $this->input->post('quantities');
			$len = count($sub_goods_ids);
			if (count($supplier_ids) == $len && count($single_prices) == $len && count($quantities) == $len)
			{
				for ($i=0; $i<$len; $i++)
				{
					if ($single_prices[$i] > 0 && $quantities[$i] > 0)
					{
						if (!$this->Suppliers_Goods_model->get_one_by_ss($sub_goods_ids[$i], $supplier_ids[$i]))
						{
							$this->data['ajax']['request'] = 'ERROR';
							$this->data['ajax']['data'] = '表单提交错误，刷新重试';
							$this->load->view('ajax_json', $this->data);
							return false;
						}
					}
					else
					{	
						$this->data['ajax']['request'] = 'ERROR';
						$this->data['ajax']['data'] = '数量和价格必须大于0';
						$this->load->view('ajax_json', $this->data);
						return false;
					}
				}
			}
			//验证结束
			$this->db->trans_begin();
			//是否管理申请单
			$pur_app_id = $this->input->post('pur_app_id');
			if ($pur_app_id)
			{
				$pur_app = $this->Purchase_Application_model->get_one($pur_app_id);
				if (empty($this->Purchase_Application_model->error) && $pur_app['pur_app_status'] == 1)
				{
					$order_id = $this->Order_model->create($pur_app_id);
					$this->Purchase_Application_model->set_status(2);
				}
				else
				{
					$this->data['ajax']['request'] = 'ERROR';
					$this->data['ajax']['data'] = __FUNCTION__ . 'UNKOWN ERROR ON LINE' . __LINE__;
					$this->load->view('ajax_json', $this->data);
					return;
				}
			}
			else
			{
				$order_id = $this->Order_model->create();
			}
			if (empty($this->Order_model->error))
			{
				$this->Order_Detail_model->create($order_id);
				if (empty($this->Order_Detail_model->error))
				{
					$this->db->trans_commit();
					$this->data['ajax']['request'] = 'CREATE_DONE';
					$this->data['ajax']['data'] = array('order_id'=>$order_id);
					$this->load->view('ajax_json', $this->data);
					return true;
				}
			}
			$this->db->trans_rollback();
			$this->data['ajax']['request'] = 'ERROR';
			$this->data['ajax']['data'] = 'UNKOWN ERROR!';
			$this->load->view('ajax_json', $this->data);
			return false;
		}
		if (0 != $pur_app_id && $pur_app = $this->Purchase_Application_model->get_one($pur_app_id))
		{
			if (empty($this->Purchase_Application_model->error))
			{
				$this->data['pur_app'] = $pur_app;
			}
		}
		$this->load->view_('order_create_view', $this->data);
	}

	public function order($order_id, $page=1)
	{

		if ('list' == $order_id)
		{
			$this->_list($page);
			return;
		}

		$order = $this->Order_model->get_one($order_id);
		if (empty($this->Order_model->error))
		{
			$this->data['order'] = $order;
			if ($order['pur_app_id'] > 0)
			{
				$pur_app = $this->Purchase_Application_model->get_one($order['pur_app_id']);
				if (empty($this->Purchase_Application_model->error))
				{
					$this->data['pur_app'] = $pur_app;
				}
			}
			$order_details = $this->Order_Detail_model->get_details($order_id);
			if (empty($this->Order_Detail_model->error))
			{
				$this->data['order_details'] = $order_details;
				$this->load->view_('order_detail_view', $this->data);
				return;
			}
			else
			{
				$this->data['error'] = $this->Order_model->error;
			}
		}
		else
		{
			$this->data['error'] = $this->Order_model->error;
		}
		$this->load->_view('error_500_view.php', $this->data);
	}

	private function _list($page=1)
	{
		$this->data['sub_menu_index'] = 4;
		$total_rows = $this->Order_model->get_total();
		$base_url = $this->data['site']['root'] . 'purchase/order/list/';
		$this->_pages($total_rows, $base_url, $page, 4);
		$start = ($page-1) * $this->limit;
		$orders = $this->Order_model->get_list($start, $this->limit);
		if (empty($this->Order_model->error))
		{
			$this->data['orders'] = $orders;
			$this->load->view_('order_list_view', $this->data);
		}
		else
		{
			$this->data['error'] = 'SYSTEM ERROR!';
			$this->load->view('error_500_view', $this->data);
		}
	}

	public function application($action, $option1=false, $option2=false)
	{
		switch($action)
		{
			case 'create':
				$this->data['sub_menu_index'] = 1;
				$this->_app_create();
				break;
			case 'update':
				$this->_app_update();
				break;
			case 'list':
				$this->data['sub_menu_index'] = 2;
				$this->_app_list($option1, $option2);
				break;
			case 'search':
				$this->_app_search();
				break;
			default :
				$this->data['error'] = '访问错误';
				$this->load->view_('error_500_view', $this->data);
		}
	}

	private function _app_create()
	{
		if ($sub_goods_ids = $this->input->post('sub_goods_ids'))
		{
			if ($this->Purchase_Application_model->create())
			{
				$this->data['ajax_request'] = 'CREATE_DONE';
			}
			else
			{
				$this->data['ajax_request'] = 'CREATE_FAILED';
			}
			$this->load->view('ajax_request', $this->data);
		}
		else
		{
			$this->load->view_('purchase_application_create_view', $this->data);
		}
	}

	private function _app_update()
	{

	}

	private function _app_list($orderby, $page=false)
	{
		$orderby = $orderby?$orderby:'timeline';
		$page = $page?$page:1;
		$total_rows = $this->Purchase_Application_model->get_all(true);
		$base_url = $this->data['site']['root'] . 'purchase/application/list/' . $orderby . '/';
		//生成分页:$this->data['page']
		$this->_pages($total_rows, $base_url, $page);
		$start = ($page-1) * $this->limit;
		$this->data['purapps'] = $this->Purchase_Application_model->get_list($start, $this->limit, $orderby);
		//var_dump($this->data['purapps']);
		//var_dump($this->data['page']);
		$this->load->view_('purchase_application_list_view', $this->data);
	}

	private function _pages($total_rows, $base_url, $page, $uri_segment=5)
	{
		$this->data['page']['total_rows'] = $total_rows;
		$this->data['page']['base_url'] = $base_url;
		$this->data['page']['per_page'] = $this->limit;
		$this->data['page']['use_page_numbers'] = TRUE;
		$this->data['page']['display_pages'] = FALSE;
		$this->data['page']['uri_segment'] = $uri_segment;
		$this->data['page']['next_link'] = '';
		$this->data['page']['next_tag_open'] = '<div id="next" class="btn">';
		$this->data['page']['next_tag_close'] = '</div>';
		$this->data['page']['prev_link'] = '';
		$this->data['page']['prev_tag_open'] = '<div id="prev" class="btn">';
		$this->data['page']['prev_tag_close'] = '</div>';
		$this->data['page']['first_tag_open'] = '<div class="hide">';
		$this->data['page']['first_tag_close'] = '</div>';
		$this->data['page']['last_tag_open'] = '<div class="hide">';
		$this->data['page']['last_tag_close'] = '</div>';
		$this->pagination->initialize($this->data['page']);
		$this->data['page']['display'] = $this->pagination->create_links();
		$this->data['page']['start'] = ($page-1) * $this->limit + 1;
		$this->data['page']['end'] = $this->data['page']['start'] + $this->limit - 1;
		if (0 == $this->data['page']['total_rows']) 
		{
			$this->data['page']['start'] = 0;
		}
		if ($this->data['page']['end'] > $this->data['page']['total_rows'])
		{
			$this->data['page']['end'] = $this->data['page']['total_rows'];
		}
	}

	//Get some values by using AJAX
	public function ajax_get_supplier_from_sub_goods()
	{
		$sub_goods_id = $this->input->post('sub_goods_id');
		if ($this->Sub_goods_model->getOne($sub_goods_id))
		{
			$suppliers_goods = $this->Suppliers_Goods_model->get_suppliers($sub_goods_id);
			$this->data['suppliers'] = array();
			foreach ($suppliers_goods as $v)
			{
				$supplier = $this->Supplier_model->getOne($v->supplier_id);
				$this->data['suppliers'][$v->supplier_id] = $supplier['supplier_name'];
			}
			$this->load->view('ajax_order_create_supplier_list_view', $this->data);
		}
		else
		{
			$this->data['ajax']['request'] = 'ERROR';
			$this->data['ajax']['data'] = '不存在子货品';
			$this->load->view('ajax_json', $this->data);
		}
	}

	//Get purchase application by using AJAX
	public function ajax_pur_app_detail()
	{
		$this->data['purapp_detail'] = $this->Purchase_Application_model->get_one();
		if (empty($this->Purchase_Application_model->error))
		{
			$this->load->view('ajax_pur_app_list_detail_view', $this->data);
		}
		else
		{
			$this->data['ajax']['request'] = 'ERROR';
			$this->data['ajax']['data'] = $this->Purchase_Application_model->error;
			$this->load->view('ajax_json', $this->data);
		}
		//var_dump($this->data['purapp_detail']);
	}

	//Set the purchase application denied
	public function ajax_purapp_denied()
	{
		$this->data['pur_app_status'] = $this->Purchase_Application_model->set_status(3);
		if (empty($this->Purchase_Application_model->error))
		{
			$this->data['ajax']['request'] = 'DENIED_DONE';
			$this->data['ajax']['data'] = '';
		}
		else
		{
			$this->data['ajax']['request'] = 'ERROR';
			$this->data['ajax']['data'] = $this->Purchase_Application_model->error;
		}
		$this->load->view('ajax_json', $this->data);
	}

	//Create a order by using AJAX
	public function ajax_order_create()
	{
		$this->create();
	}

	public function ajax_purapp_confirm()
	{
		$pur_app_id = $this->input->post('pur_app_id');
		$pur_app = $this->Purchase_Application_model->get_one($pur_app_id);
		if (empty($this->Purchase_Application_model->error) && $pur_app['pur_app_status'] == 1)
		{
			$this->data['ajax']['request'] = 'DONE';
			$this->data['ajax']['data'] = $pur_app['pur_app_id'];
			$this->load->view('ajax_json', $this->data);
		}
		else
		{
			$this->data['ajax']['request'] = 'ERROR';
			$this->data['ajax']['data'] = $this->Purchase_Application_model->error;
			$this->load->view('ajax_json', $this->data);
		}
	}

}